import "./index.less";

const welcome = {};

welcome.newInstance = Vue => {
  let welcomeElement = document.querySelector("body>div[type=welcome]");
  if (!welcomeElement) {
    welcomeElement = document.createElement("div");
    welcomeElement.setAttribute("type", "welcome");
    document.body.appendChild(welcomeElement);
  }

  const cdProps = { visible: false, opacity: 1, clazz: "" };

  const instance = new Vue({
    data() {
      return {
        ...cdProps,
      };
    },
    render() {
      if (this.visible) {
        return (
          <div class="welcome" style={{ opacity: this.opacity }}>
            <div class={`main ${this.clazz}`}>{window.vm.$store.state.user.nickname && window.vm.$i18n.t("hello") + "，" + window.vm.$store.state.user.nickname + "！"}</div>
            <div class={`msg ${this.clazz}`}>{window.vm.$i18n.t("welcome") + " " + window.vm.$i18n.t("title")}</div>
          </div>
        );
      }
      return null;
    },
  }).$mount(welcomeElement);

  return instance;
};

const api = {
  show: function() {
    this.instance.$set(this.instance, "visible", true);
    this.instance.$set(this.instance, "opacity", 1);
    this.instance.$set(this.instance, "clazz", "");

    this.clazzT && clearTimeout(this.clazzT);
    this.clazzT = setTimeout(() => {
      this.instance.$set(this.instance, "clazz", "anim-drop");
    }, 100);

    this.hideT && clearTimeout(this.hideT);
    this.hideT = setTimeout(() => this.hide(), 2000); //延迟2秒后自动关闭
  },
  hide: function() {
    this.instance.$set(this.instance, "visible", true);
    this.instance.$set(this.instance, "opacity", 0);

    this.visibleT && clearTimeout(this.visibleT);
    this.visibleT = setTimeout(() => this.instance.$set(this.instance, "visible", false), 1000);
  },
};

const install = function(Vue) {
  if (Vue.prototype.$welcome) {
    return;
  }
  api.instance = welcome.newInstance(Vue);
  Vue.prototype.$welcome = api;
};

export default install;
